package com.example.demo.controller;

import com.example.demo.main.*;
import com.example.demo.main.Collection;
import com.example.demo.mapper.*;
import com.example.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/User")
public class UserDataController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserExample userExample;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserCartMapper userCartMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private AddressExample addressExample;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreExample storeExample;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SelectByGoodsImpl selectByGoods;
    @Autowired
    private UseSQLByStore useSQLByStore;
    @Autowired
    private UseSQLByCart useSQLByCart;
    @Autowired
    private UseSQLOfCollection useSQLOfCollection;
    @Autowired
    private UseSQLOfOrder useSQLOfOrder;
    @Autowired
    private UseSQLOfPayWay useSQLOfPayWay;

    @Autowired
    private GoodsService goodsService;


    private static final File FILE = new File("upload/");


    @RequestMapping("/Login/checkNameAndPwd")//登录验证
    public String CheckNameAndPwd(String userName, String userPwd, HttpServletRequest request) {
        userExample.or().andUserNameEqualTo(userName).andUserPwdEqualTo(userPwd);
        if (userMapper.selectByExample(userExample).size() > 0) {
            userExample.clear();
            ShowCart showCart = userService.showCartPriceAndCount(userName);
            request.getSession().setAttribute("cartCount", showCart.getCount());
            request.getSession().setAttribute("cartPrice", showCart.getPrice());
            request.getSession().setAttribute("userName", userName);
            request.getSession().setAttribute("loginUrl", "/User/userdetail");
            return "yes";
        }
        userExample.clear();
        return "no";
    }

    @RequestMapping("/Register/checkName")//注册，登录检查用户名是否存在
    public String CheckName(String userName) {
        if (userMapper.selectByPrimaryKey(userName) != null) {
            return "yes";
        }
        return "no";
    }

    @RequestMapping("/Register/data")//注册交互
    public String DataRegister(User user) {
        if (user.getUserName() != null && user.getUserName() != "") {
            userService.toRegister(user);
            return "yes";
        }
        return "no";
    }

    @RequestMapping("/address/data")//添加地址,修改地址
    public String DataAddress(Address address, HttpServletRequest request, Long moren, Long flag) {
        address.setUserName((String) request.getSession().getAttribute("userName"));
        if (flag == 0) {
            if ((address.getAddress() != null || address.getPersion() != null || address.getPhone() != null)
                    && (!address.getAddress().equals("") || !address.getPersion().equals("") || !address.getPhone().equals(""))) {
                if (address.getRole() == 1) {
                    Address addr = new Address();
                    addr.setId(moren);
                    addr.setRole(0);
                    addressMapper.updateByPrimaryKeySelective(addr);
                }
                addressMapper.insertSelective(address);
                return "yes";
            } else {
                return "no";
            }
        } else {
            address.setId(flag);
            addressMapper.updateByPrimaryKey(address);
            return "yes";
        }

    }

    @RequestMapping("/addressChange/data")//改变默认地址role=1为默认,moern为原来默认地址id
    public String DataAdrChange(Long id, Long moren) {
        if (id != null || moren != null) {
            if (id.equals(moren)) return "yes";
            Address address = new Address();
            address.setId(moren);
            address.setRole(0);
            addressMapper.updateByPrimaryKeySelective(address);
            address.setId(id);
            address.setRole(1);
            addressMapper.updateByPrimaryKeySelective(address);
            return "yes";
        }
        return "no";
    }

    @RequestMapping("/addressDelete/data")//删除地址
    public String DataAdrDelete(Long id) {
        if (id != null) {
            addressMapper.deleteByPrimaryKey(id);
            return "yes";
        }
        return "no";
    }

    @RequestMapping("/pwdChange/data")//更改密码
    public String DataPwdChange(String OldPwd, String NewPwd, HttpServletRequest request) {
        if (OldPwd.equals(NewPwd)) return "yes";
        String userName = (String) request.getSession().getAttribute("userName");
        User user = new User();
        user.setUserPwd(NewPwd);
        user.setUserName(userName);
        if (userMapper.updateByPrimaryKeySelective(user) > 0) {
            return "yes";
        }
        return "no";
    }

    @RequestMapping("/DeleteCart/data")//删除购物车
    public String DeleteCart(Long id, HttpServletRequest request) {
        if (id != null) {
            String userName = userCartMapper.selectByPrimaryKey(id).getUserName();
            int rid = userCartMapper.deleteByPrimaryKey(id);
            ShowCart showCart = userService.showCartPriceAndCount(userName);
            request.getSession().setAttribute("cartCount", showCart.getCount());
            request.getSession().setAttribute("cartPrice", showCart.getPrice());
            if (rid > 0)
                return "yes";
            else
                return "no";
        } else
            return "no";
    }

    @RequestMapping("/updateUserCart/data")//更新购物车
    public String DataUpdateCart(@RequestBody Map<String, String> map, HttpServletRequest request) {
        int flag = 0;
        if (map.size() > 0) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                Long rid = Long.valueOf(entry.getKey());
                Integer count = Integer.valueOf(entry.getValue());
                UserCart userCart = new UserCart();
                userCart.setRid(rid);
                userCart.setCount(count);
                flag = flag + userCartMapper.updateByPrimaryKeySelective(userCart);
                ShowCart showCart = userService.showCartPriceAndCount(userCartMapper.selectByPrimaryKey(rid).getUserName());
                request.getSession().setAttribute("cartCount", showCart.getCount());
                request.getSession().setAttribute("cartPrice", showCart.getPrice());
            }
        }
        if (flag > 0) {
            return "yes";
        } else return "no";
    }

    @RequestMapping("/CartCreatOrder/data")//购物车创建订单
    public String DataCreatOrder(@RequestBody String[] myArray, HttpServletRequest request) {
        int flag = 0;
        String userName = (String) request.getSession().getAttribute("userName");
        String storeName = useSQLByStore.selectByUsrName(userName).get(0).getStoreName();
        for (String cartID : myArray
        ) {
            if (cartID != null) {
                Long rid = Long.valueOf(cartID);
                UserCart userCart = userCartMapper.selectByPrimaryKey(rid);
                BigDecimal price = new BigDecimal("0.00");
                for (int i = 0; i < userCart.getCount(); i++) {
                    price = price.add(userCart.getPrice());
                }
                String orderID = Long.toString(System.currentTimeMillis());
                Date date = new Date();
                if (!useSQLOfOrder.selectByRemoveDateLessAndDelete(date)) {
                    try {
                        useSQLOfOrder.selectByRemoveDateLessAndDelete(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, 3);
                    Date removeDate = calendar.getTime();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String time = formatter.format(date);
                    UserOrder order = new UserOrder(orderID, storeName, userName, null, time, removeDate,
                            null, userCart.getCount(), "未支付", price,
                            null, userCart.getGoodsPicture(), userCart.getGoodsName());
                    flag = flag + userOrderMapper.insert(order);
                    userCartMapper.deleteByPrimaryKey(rid);
                }
            }
        }
        if (flag > 0) {
            ShowCart showCart = userService.showCartPriceAndCount(userName);
            request.getSession().setAttribute("cartCount", showCart.getCount());
            request.getSession().setAttribute("cartPrice", showCart.getPrice());
            return "yes";
        } else return "no";
    }


    @RequestMapping("/storeRegister/Data")//店铺注册
    public String DataPwdChange(Store store, HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute("userName");
        store.setUserName(userName);
        int flag = 0;
        flag = storeMapper.insertSelective(store);
        if (flag > 0) return "yes";
        else return "no";
    }


    @RequestMapping("/upload/data")
    public String upload(@RequestParam("uploadFile") MultipartFile[] uploadFile, Goods goods, HttpServletRequest
            request) {
        String userName = (String) request.getSession().getAttribute("userName");
        storeExample.or().andUserNameEqualTo(userName);
        Store store = storeMapper.selectByExample(storeExample).get(0);
        goods.setStoreId(store.getStoreId());
        String storeName = store.getStoreName();
        storeExample.clear();
        String backMsg = null;
        goods.setEvaluationCount(0);
        goods.setCollectionCount(0);
        if (uploadFile == null) {
            backMsg = "上传失败,无法找到文件!";
            return backMsg;
        }
        int i = 0;
        for (MultipartFile file : uploadFile
        ) {
            String fileName = file.getOriginalFilename();
            if (fileName != null && fileName.contains(".")) {
                fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            }
            String filePath = FILE.getAbsolutePath() + "/" + storeName + "/" + goods.getGoodsName() + "/";
            String SQLPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/image/" + storeName + "/" + goods.getGoodsName() + "/" + fileName;
            switch (i) {
                case 0:
                    goods.setGoodsPicture1(SQLPath);
                    break;
                case 1:
                    goods.setGoodsPicture2(SQLPath);
                    break;
                case 2:
                    goods.setGoodsPicture3(SQLPath);
                    break;
                case 3:
                    goods.setGoodsPicture4(SQLPath);
                    break;
                case 4:
                    goods.setGoodsPicture5(SQLPath);
                    break;
                default:
                    backMsg = "文件上传错误";
            }
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(filePath + fileName);
                out.write(file.getBytes());
                out.flush();
                out.close();
                backMsg = "上传成功!";
            } catch (IOException e) {
                e.printStackTrace();
                backMsg = "上传失败!";
                break;
            }
            i++;
        }
        if (goodsMapper.insertSelective(goods) < 1)
            backMsg = "上传失败?!";
        return backMsg;
    }

    @RequestMapping("/upCount/data")
    public String upCountData(Goods goods) {
        if (goodsMapper.updateByPrimaryKeySelective(goods) == 1)
            return "yes";
        else return "no";
    }

    @RequestMapping("/deleteGoods/data")
    public String deleteGoods(Long goodsId) {
        String msg = "no";
        System.out.println("删除商品：" + goodsService.deleteGoods(goodsId, FILE));
        return msg;
    }


    @RequestMapping("/updatePrice/data")
    public String updatePrice(Goods goods) {
        if (goodsMapper.updateByPrimaryKeySelective(goods) > 0)
            return "yes";
        else return "no";
    }


    @RequestMapping("/addOrder/Data")//直接购买
    public String addOrder(Long id, Integer count, HttpServletRequest request) {
        Date date = new Date();
        String msg = "no";
        String userName = (String) request.getSession().getAttribute("userName");
        Goods goods = selectByGoods.selectById(id);
        String orderID = Long.toString(System.currentTimeMillis());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, 3);
        Date removeDate = calendar.getTime();
        BigDecimal price = new BigDecimal("0.00");
        for (int i = 0; i < count; i++) {
            price = price.add(goods.getPrice());
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String time = formatter.format(date);
        String storeName = useSQLByStore.selectById(goods.getStoreId()).getStoreName();
        UserOrder userOrder = new UserOrder(orderID, storeName, userName, null, time, removeDate, null,
                count, "未支付", price, null, goods.getGoodsPicture1(), goods.getGoodsName());
        if (useSQLOfOrder.insertByClass(userOrder) > 0) msg = "yes";
        return msg;
    }


    @RequestMapping("/addCart/Data")//详情页加入购物车
    public String addCart(Long id, Integer count, HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute("userName");
        Goods goods = selectByGoods.selectById(id);
        List<UserCart> userCartList = useSQLByCart.selectByGoodsName(goods.getGoodsName());
        if (userCartList.size() > 0) {
            count += userCartList.get(0).getCount();
            Long rid = userCartList.get(0).getRid();
            if (useSQLByCart.updateByClass(new UserCart(rid, count)) > 0) {
                return "yes";
            } else return "no";
        } else {
            String storeName = useSQLByStore.selectById(goods.getStoreId()).getStoreName();
            UserCart userCart = new UserCart(null, userName, goods.getGoodsName(), count, goods.getGoodsPicture1(), storeName, goods.getPrice());
            if (useSQLByCart.insertByClass(userCart) > 0) {
                ShowCart showCart = userService.showCartPriceAndCount(userName);
                request.getSession().setAttribute("cartCount", showCart.getCount());
                request.getSession().setAttribute("cartPrice", showCart.getPrice());
                return "yes";
            } else return "no";
        }
    }

    @RequestMapping("/addWishlist/Data")
    public String addWishlist(Long id, HttpServletRequest request) {
        if (useSQLOfCollection.selectByGoodsID(id).size() > 0) return "yes";
        String userName = (String) request.getSession().getAttribute("userName");
        Goods goods = selectByGoods.selectById(id);
        Collection collection = new Collection(null, userName, id, goods.getPrice(), goods.getGoodsPicture1(), goods.getGoodsName(), goods.getEvaluationCount());
        if (useSQLOfCollection.insertByClass(collection) > 0) {
            Integer newCount = selectByGoods.selectById(id).getCollectionCount() + 1;
            Goods goods1 = new Goods(id, newCount);
            if (selectByGoods.updateByGoods(goods1) > 0)
                return "yes";
        }
        return "no";
    }

    @RequestMapping("/deleteOrder/data")
    public String deleteOrder(String orderID) {
        if (useSQLOfOrder.deleteByID(orderID) > 0)
            return "yes";
        else return "no";
    }

    @RequestMapping("/updateOrder/data")
    public String updateOrder(String way, UserOrder userOrder) {
        List<UserOrder> orderList = useSQLOfOrder.selectNoPay();
        String goodsName = orderList.get(0).getGoodsName();
        for (UserOrder order : orderList
        ) {
            useSQLOfPayWay.insertByClass(new PayWay(order.getOrderId(), way));
        }
        if (useSQLOfOrder.updateNoPay(userOrder) > 0 && selectByGoods.subCount(goodsName) > 0) return "yes";
        else return "no";
    }

    @RequestMapping("/updateStoreOrder/data")
    public String updateStoreOrder(String orderId) {
        if (useSQLOfOrder.updateStoreorder(orderId) > 0)
            return "yes";
        else return "no";
    }
}
